package com.linln.devtools.generate;

import com.linln.devtools.generate.domain.Field;
import com.linln.devtools.generate.enums.FieldType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;

/**
 * 处理数据库表信息
 */
@Service
@Slf4j
public class TableService {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 获取表名的所有字段信息
     *
     * @param table
     * @return
     */
    public List<Field> getTableFields(String table) {
        if (!StringUtils.hasText(table)) {
            return DefaultValue.fieldList();
        }
        try {
            String sql = "";
            return jdbcTemplate.query("SHOW FULL COLUMNS FROM `" + table + "`", new RowMapper<Field>() {
                @Override
                public Field mapRow(ResultSet rs, int i) throws SQLException {
                    String field = rs.getString("Field");//字段名
                    String type = rs.getString("Type");//字段类型
                    String isNull = rs.getString("Null");//是否可为空
                    String key = rs.getString("Key");//主键类型：PRI为主键
                    String comment = rs.getString("Comment");//注释，可作为标题
                    Field f = new Field();
                    f.setName(field);
                    f.setTitle(comment);
                    f.setQuery(0);
                    f.setVerify(null);
                    f.setShow(true);
                    f.setType(convertType(type));
                    return f;
                }
            }).stream().filter(x -> x != null).collect(Collectors.toList());
        } catch (Exception e) {
            log.warn(e.getMessage(), e);
            return DefaultValue.fieldList();
        }
    }

    /**
     * 根据数据库类型，转换对FieldType定义的类型
     *
     * @param type
     * @return
     */
    private Integer convertType(String type) {
        if (!StringUtils.hasText(type)) {
            return FieldType.String.getCode();
        }
        type = type.trim().toLowerCase();
        //把长度定义去掉
        String len = "";
        if (type.contains("(") && type.contains(")")) {
            len = type.substring(type.indexOf("(") + 1, type.indexOf(")"));
            type = type.substring(0, type.indexOf("("));
        }
        if (type.startsWith("varchar")) {
            return FieldType.String.getCode();
        } else if (type.equals("bigint")) {
            return FieldType.Long.getCode();
        } else if (type.equals("tinyint")) {
            return FieldType.Byte.getCode();
        } else if (type.endsWith("int")) {
            try {
                if(Integer.parseInt(len)>9){
                    return FieldType.Long.getCode();
                }
            } catch (Exception e) {
            }
            return FieldType.Integer.getCode();
        } else if (type.endsWith("clob") || type.endsWith("text")) {
            return FieldType.Text.getCode();
        } else if (type.startsWith("date") || type.startsWith("time")) {
            return FieldType.Date.getCode();
        } else if (type.equals("float")) {
            return FieldType.Float.getCode();
        } else if (type.equals("double")) {
            return FieldType.Double.getCode();
        } else if (type.equals("decimal") || type.equals("numeric")) {
            return FieldType.BigDecimal.getCode();
        }
        return FieldType.String.getCode();
    }
}
